package com.drinking.consumerwithhystrix.controller;

import com.drinking.consumerwithhystrix.hystrix.MyHystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
public class HelloController {

    private String providerUrl = "http://PROVIDER/";

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/")
    public String hello(){
        return "hello";
    }

    @RequestMapping("/test")
    public String test(){
        ResponseEntity<String> response = restTemplate.getForEntity(providerUrl+"test",String.class);
//        System.out.println(response.getStatusCode());
//        System.out.println(response.getHeaders());

//        restTemplate.postForObject();

        return response.getBody();
    }

    @RequestMapping("/test02")
    @HystrixCommand(fallbackMethod = "error")
    public String test02(){
        return restTemplate.getForObject(providerUrl+"test02",String.class);
    }

    @RequestMapping("/test025")
    @HystrixCommand(fallbackMethod="error",
                    commandProperties={
                        @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3500")}
                    )
    public String test025(){
        return restTemplate.getForObject(providerUrl+"test02",String.class);
    }

    @RequestMapping("/test03")
    @HystrixCommand(fallbackMethod = "error")
    public String test03(){
        return restTemplate.getForObject(providerUrl+"test03",String.class);
    }

    @RequestMapping("/test04")
    @HystrixCommand(fallbackMethod = "error")
    public String test04(){
        int i = 10/0;
        return restTemplate.getForObject(providerUrl+"test01",String.class);
    }

    @RequestMapping("/test05")
    public String test05(){
        String url = providerUrl+"test03";
        MyHystrixCommand hc = new MyHystrixCommand(com.netflix.hystrix.HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("")), restTemplate,url);
        return (String) hc.execute();
    }

    @RequestMapping("/test06")
    public String test06(){
        int i = 10/0;
        return "test06";
    }

    public String error(Throwable throwable){
        return "服务熔断:"+throwable;
    }


}
